package com.pet.config;

import com.pet.exceptions.BusinessException;
import com.pet.shop.utils.ApiResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@ControllerAdvice
public class WebControllerAdvice {

    protected static final Logger logger = LoggerFactory.getLogger(WebControllerAdvice.class);

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> errorHandler(Exception ex) {
        logger.error("捕捉到异常", ex);
        return ApiResultUtil.error_param(ex.getMessage());
    }

    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Map<String, Object> myErrorHandler(BusinessException ex) {
        logger.error("捕捉到异常", ex);
        return ApiResultUtil.error_param(ex.getMessage());
    }
}
